package com.fin.zw.intelligentbot.service;

import com.fin.zw.intelligentbot.entity.QResource;
import com.fin.zw.intelligentbot.entity.QRoleInfo;
import com.fin.zw.intelligentbot.entity.Resource;
import com.fin.zw.intelligentbot.entity.RoleInfo;
import com.fin.zw.intelligentbot.model.session.SessionModel;
import com.fin.zw.intelligentbot.repository.ResourceRepository;
import com.fin.zw.intelligentbot.repository.RoleInfoRepository;
import com.querydsl.core.BooleanBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.Iterator;
import java.util.List;
import java.util.Optional;

@Service("resourceService")
public class ResourceService {

    private static final Logger log = LoggerFactory.getLogger(ResourceService.class);

    @Autowired
    private ResourceRepository resourceRepository;

    @Autowired
    private RoleInfoRepository roleInfoRepository;

    @Autowired
    private CommonService commonService;

    /**
     * 查询所有菜单信息（分页）
     * @param pageable
     * @param request
     * @return
     */
    public Page<Resource> queryResourceAll(Pageable pageable,Resource request){
        BooleanBuilder builder = new BooleanBuilder();
        QResource qResource = QResource.resource;
        if(request.getName() != null){
            builder.and(qResource.name.eq(request.getName()));
        }
        if(request.getType() != null){
            builder.and(qResource.type.ne(request.getType()));
        }
        Page<Resource> page = resourceRepository.findAll(builder,pageable);
        return page;
    }

    /**
     * 查询所有的菜单信息
     * @return
     */
    public List<Resource> getResourceList(SessionModel sessionModel){
        if(commonService.whetherAdmin(sessionModel)){
            return resourceRepository.findAll();
        }else{
            List<Resource> list = sessionModel.getResources();
            return list;
        }
    }

    /**
     * 菜单的添加
     * @param resource
     */
    public void createResource(Resource resource){
        resourceRepository.save(resource);
    }

    /**
     * 菜单的修改
     * @param resource
     */
    public void updateResource(Resource resource){
        Optional<Resource> optional = resourceRepository.findById(resource.getId());
        if(!optional.isPresent()){
            log.info("修改菜单信息不存在");
            throw new RuntimeException("修改菜单信息不存在");
        }
        Resource res = optional.get();
        BeanUtils.copyProperties(resource,res);
        resourceRepository.save(res);
    }

    /**
     * 菜单的删除
     * @param id
     */
    public void deleteResourceById(String id){
        Optional<Resource> optional = resourceRepository.findById(id);
        if(!optional.isPresent()){
            log.info("删除菜单信息不存在");
            throw new RuntimeException("删除菜单信息不存在");
        }
        Resource resource = optional.get();

        Iterator<Resource> iterator = resourceRepository.findAll(QResource.resource.parentId.eq(id)).iterator();
        if(iterator.hasNext()){
            log.info("菜单下存在子菜单，不允许删除");
            throw new RuntimeException("菜单下存在子菜单，不允许删除");
        }
        Iterator<RoleInfo> roleInfoIterator = roleInfoRepository.findAll(QRoleInfo.roleInfo.resources.contains(resource)).iterator();
        if(roleInfoIterator.hasNext()){
            log.info("该菜单已经被角色绑定，请先解绑");
            throw new RuntimeException("该菜单已经被角色绑定，请先解绑");
        }
        resourceRepository.delete(resource);
    }
}
